package cn.javazd.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.helpers.AttributesImpl;

public class SaxXml implements Xml {
	
	static List<Iphone> phones = new ArrayList<Iphone>();
	
	static {
		Iphone phone = new Iphone();
		phone.setColor("磨砂黑");
		phone.setVersion("1.0");
		phone.setName("iphone 8");
		phones.add(phone);
	}

	@Override
	public void createXml() {
		long startTime = System.currentTimeMillis();
		SAXTransformerFactory tff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
		try {
			TransformerHandler handler = tff.newTransformerHandler();
			Transformer tr = handler.getTransformer();
			tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			tr.setOutputProperty(OutputKeys.INDENT, "yes");
			
			File file = new File("Sax-app.xml");
			Result result = new StreamResult(new FileOutputStream(file));
			
			handler.setResult(result);
			handler.startDocument();
			
			AttributesImpl attr = new AttributesImpl();
			handler.startElement("", "", "app", attr);
            attr.clear();
			
            for (Iphone phone : phones) {
				attr.clear();
				handler.startElement("", "", "iphone", attr);
				
				attr.clear();
				attr.addAttribute("", "", "type", "", "IOS 11.1");
				handler.startElement("", "", "version", attr);
				handler.characters(phone.getVersion().toCharArray(), 0, phone.getVersion().length());
				handler.endElement("", "", "version");
				
				attr.clear();
				handler.startElement("", "", "name", attr);
				handler.characters(phone.getName().toCharArray(), 0, phone.getName().length());
				handler.endElement("", "", "name");
				
				attr.clear();
				handler.startElement("", "", "color", attr);
				handler.characters(phone.getColor().toCharArray(), 0, phone.getColor().length());
				handler.endElement("", "", "color");
				
				
				handler.endElement("", "", "iphone");
			}
            handler.endElement("", "", "app");
			handler.endDocument();
			System.out.print("create Sax xml success ==== ");
			System.out.println("speed times: " + (System.currentTimeMillis() - startTime));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

class Iphone {
	
	String version;
	String name;
	String color;

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}
}
